package my.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import my.db.Student;
import my.db.Teacher;

@Component
@WebFilter("/*")
public class SimpleFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		// login.html 可以直接 访问
				String servletPath = request.getServletPath();
								
				String[] urls = {"/login","/json",".js",".css",".png",".jpg",".do"};
				boolean flag = false;
				for (String url : urls) {
					if(servletPath.indexOf(url) != -1) {
						flag = true;
					}
				}
		if(flag)
		{
			chain.doFilter(request, response);
			return;
		}
		// 其他页面需要登录后才能访问
		HttpSession session = request.getSession();
		Student student = (Student) session.getAttribute("student");
		Teacher teacher = (Teacher) session.getAttribute("teacher");

		if(student == null && teacher == null)
		{
			// 重定向到 /login.html
			response.sendRedirect("login");
			return;  
		}
		
		// 调用 chain.doFilter()表示 '通过'
		chain.doFilter(request, response);
	}

}
